package com.djl.mymall.service.impl;

import com.djl.mymall.common.CommonResult;
import com.djl.mymall.service.MenberService;
import com.djl.mymall.service.RedisService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * @author djl
 * @projectName myMall
 * @description: 会员管理service实现类
 * @date 2022/1/180:32
 */
@Service
public class MenberServiceImpl implements MenberService {
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTHCODE;
    @Value("${redis.key.expire.authCode}")
    private  int REDIS_KEY_EXPIRE_AUTHCODE;
    @Override
    public CommonResult generateAuthCode(String telephone) {
        Random random=new Random();
        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        redisService.expire(REDIS_KEY_PREFIX_AUTHCODE+telephone,REDIS_KEY_EXPIRE_AUTHCODE);
        redisService.set(REDIS_KEY_PREFIX_AUTHCODE+telephone,stringBuilder.toString());

        return CommonResult.success(stringBuilder.toString());
    }

    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)){
            return CommonResult.failed("请输入验证码");
        }
       String realAuthCode=  redisService.get(REDIS_KEY_PREFIX_AUTHCODE+telephone);
        if (!authCode.equals(realAuthCode)){
            return CommonResult.success("输入验证码失败");
        }
        return CommonResult.success("验证成功");
    }


}
